package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * 小视频服务实现类
 */
@Service
public class VideoApiImpl implements  VideoApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 发布小视频
     * @param video
     */
    @Override
    public void saveVideo(Video video) {
        video.setId(ObjectId.get());//主键id
        video.setVid(1l);//处境id
        video.setText("分手快乐");//文字 写死
        video.setCreated(System.currentTimeMillis());//发布小视频时间
        mongoTemplate.save(video);
    }

    /**
     * 分页查询小视频列表
     */
    @Override
    public PageResult<Video> queryPage(int page, int pagesize) {
        //1.查询小视频表总记录数
        Query query = new Query();
        query.limit(pagesize).skip((page - 1) * pagesize);
        //根据时间排序（将时间最新的在最上面展示）
        query.with(Sort.by(Sort.Direction.DESC,"created"));
        long counts = mongoTemplate.count(query, Video.class);
        //2.查询当前页面要展示的数据
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        //3.将数据封装返回
        long pages = (counts / pagesize) + (counts%pagesize > 0 ? 1:0);
        return new PageResult<>(counts,(long)pagesize,pages,(long)page,videoList);
    }
}
